#!/usr/bin/env python3
"""
简单的HTTPS服务器，用于测试麦克风权限
需要先安装依赖：pip install pyOpenSSL
"""

import http.server
import ssl
import socketserver
import os

# 服务器配置
PORT = 8443
HOST = '0.0.0.0'  # 允许外部访问

class MyHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
    def end_headers(self):
        # 添加CORS头，允许跨域访问
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type')
        super().end_headers()

def create_self_signed_cert():
    """创建自签名证书"""
    try:
        from OpenSSL import crypto, SSL
        
        # 创建密钥对
        key = crypto.PKey()
        key.generate_key(crypto.TYPE_RSA, 2048)
        
        # 创建证书
        cert = crypto.X509()
        cert.get_subject().C = "CN"
        cert.get_subject().ST = "Beijing"
        cert.get_subject().L = "Beijing"
        cert.get_subject().O = "Meeting Assistant"
        cert.get_subject().OU = "Development"
        cert.get_subject().CN = "localhost"
        cert.set_serial_number(1000)
        cert.gmtime_adj_notBefore(0)
        cert.gmtime_adj_notAfter(365*24*60*60)  # 1年有效期
        cert.set_issuer(cert.get_subject())
        cert.set_pubkey(key)
        cert.sign(key, 'sha256')
        
        # 保存证书和密钥
        with open('server.crt', 'wb') as f:
            f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
        with open('server.key', 'wb') as f:
            f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, key))
            
        print("✅ 自签名证书创建成功")
        return True
        
    except ImportError:
        print("❌ 需要安装 pyOpenSSL: pip install pyOpenSSL")
        return False
    except Exception as e:
        print(f"❌ 创建证书失败: {e}")
        return False

def main():
    # 检查证书是否存在
    if not (os.path.exists('server.crt') and os.path.exists('server.key')):
        print("🔐 创建自签名证书...")
        if not create_self_signed_cert():
            print("❌ 无法创建证书，请手动安装 pyOpenSSL")
            return
    
    # 创建HTTPS服务器
    with socketserver.TCPServer((HOST, PORT), MyHTTPRequestHandler) as httpd:
        # 配置SSL
        context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
        context.load_cert_chain('server.crt', 'server.key')
        httpd.socket = context.wrap_socket(httpd.socket, server_side=True)
        
        print(f"🚀 HTTPS服务器启动成功!")
        print(f"📱 访问地址: https://{HOST}:{PORT}")
        print(f"🌐 外部访问: https://10.151.124.38:{PORT}")
        print("⚠️  浏览器会显示安全警告，请点击'高级' -> '继续访问'")
        print("🎤 现在可以正常使用麦克风功能了!")
        print("\n按 Ctrl+C 停止服务器")
        
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            print("\n👋 服务器已停止")

if __name__ == "__main__":
    main()
